package com.googlecode.bpmcenter.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.bpmn.diagram.ProcessDiagramGenerator;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.googlecode.bpmcenter.util.IOUtil;

public class DiagramServlet extends HttpServlet {

	private static final long serialVersionUID = -5106292230306205506L;
	
	private RepositoryService repositoryService;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
	  super.init(config);
	  WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
	  this.repositoryService = (RepositoryService) springContext.getBean("repositoryService");
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String key = request.getParameter("key");
		if (key == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		InputStream is = getProcessDefinitionImage(key);
		if (is == null) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		OutputStream os;
		try {
			
			os = response.getOutputStream();
			IOUtil.copyStream(is, os);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public InputStream getProcessDefinitionImage(String key) {

		InputStream ret = null;
		List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery()
		    .processDefinitionKey(key).list();

		int size = processDefinitions.size();
		if ((processDefinitions != null) && size > 0) {
			ProcessDefinition processDefinition = processDefinitions.get(size - 1);
			
			BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
			List<String> highlightActivities = new ArrayList<String>();
			ret = ProcessDiagramGenerator.generateDiagram(model, "png", highlightActivities );
			
		}
		return ret;
	}

}